var express = require('express');
var router = express.Router();
const md5 = require('md5');
const user = require('../model/user');
const article = require('../model/article');
const collect = require('../model/collect');
const sd =  require('silly-datetime');
/* GET home page. */

// 注册接口
router.post('/register', function (req, res) {
  let obj = {
    ...req.body,
    ...{
      token: md5(req.body.nickname + req.body.password)
    }
  }
  user.find({ user: req.body.nickname }).then(data => {
    if (data.length > 0) {
      res.send({ status: 200, success: false, msg: '该用户已存在！' })
    } else {
      user.create(obj).then(() => {
        res.send({ status: 200, success: true, msg: '注册成功' })
      }).catch(() => {
        res.send({ status: 200, success: false, msg: '注册失败' })
      })
    }
  })

});

// 登录接口
router.post('/login', (req, res) => {
  user.find(req.body).then(data => {
    if (data.length > 0) {
      res.send({
        status: 200, success: true, msg: '登录成功', data: {
          nickname: data[0].nickname,
          token: data[0].token
        }
      })
    } else {
      res.send({ status: 200, success: false, msg: '用户名或者密码错误' })
    }
  })
})

// 退出登录
router.get('/loginout', (req, res) => {
  res.send({ status: 200, success: true, msg: '退出成功' })
})

// 文章保存接口
router.post('/save', async (req, res) => {
  let obj = {
    ...req.body,
    token: req.headers.token,
    star: 0,
    time: sd.format(new Date(), 'YYYY-MM-DD HH:mm')
  }
  if (!obj.token) {
    res.send({ status: 200, success: false, msg: '请先登录' })
    return;
  }
  
  let data = await user.find({token:req.headers.token});
  if (data.length===0){
    res.send({ status: 200, success: false, msg: '非法token' });
    return;
  }
  
  article.create(obj).then(() => {
    res.send({ status: 200, success: true, msg: '保存成功' })
  }).catch(() => {
    res.send({ status: 200, success: false, msg: '保存失败' })
  })
})

// 文章查询列表
router.get('/paper/list', async (req, res) => {
  let total = await article.count();
  let page = req.query.page;
  let pageSize = req.query.pageSize;
  article.aggregate([
    {
      $lookup:
      {
        from: "users",
        localField: "token",
        foreignField: "token",
        as: "author"
      }
    },
    {
      $skip: (page*1 - 1) * pageSize*1
    },
    {
      $limit: pageSize*1
    }
  ]).then(data => {
    res.send({ status: 200, success: true, msg: '查询成功', data:{
      total: total,
      list: data
    }})
  }).catch(() => {
    res.send({ status: 200, success: false, msg: '查找失败' })
  })
})


// 专题列表
router.get('/special/list', async (req, res) => {
  let total = await article.count({ token: req.query.author });
  let [author] = await user.find({token:req.query.author});
  let page = req.query.page;
  let token = req.headers.token;
  let pageSize = req.query.pageSize;
  let collectData = null;
  if (token){
     collectData = await collect.find();
  }
  
  article.find({ token: req.query.author }).skip((page*1 - 1) * pageSize*1).limit(pageSize*1).sort({time:-1}).then(data => {
    if (token) {
      data.forEach(item => {
        item.star = collectData.some(n => n.mixed == (item._id +'-'+ token)) ? 1 : 2
      })
    }
    let obj = { 
      nickname: author.nickname, 
      description: "我与春风皆过客，你携秋水揽星河。星光不问赶路人，时光不负有心人。只言温暖，莫问伤悲！",
      authorImg: data.find(item => item.img)?data.find(item => item.img).img:'',
      list: data };
    res.send({ status: 200, success: true, msg: '查询成功', data:{
      content: obj,
      total: total
    }})
  }).catch(() => {
    res.send({ status: 200, success: false, msg: '查找失败' })
  })
})



// 收藏的接口
router.get('/collect', (req, res) => {
  let id = req.query.id;
  let token = req.headers.token;
  if (!token) {
    res.send({ status: 200, success: false, msg: '请先登录' })
    return;
  }
  collect.find({ id: id }).then(data => {
    if (data.length > 0) {
      collect.remove({ id: id }).then(() => {
        res.send({ status: 200, success: true, msg: '取消收藏成功！' })
      }).catch(() => {
        res.send({ status: 200, success: false, msg: '取消收藏失败！' })
      })
    } else {
      collect.create({ token: token, id: id, mixed: id +'-'+ token }).then(() => {
        res.send({ status: 200, success: true, msg: '收藏成功！' })
      }).catch(() => {
        res.send({ status: 200, success: false, msg: '收藏失败！' })
      })
    }
  })
})


// 删除 
router.get('/remove', async (req, res) => {
  let [data] = await article.find({ _id: req.query.id });
  let token = req.headers.token;
  if (data.token !== token) {
    res.send({ status: 200, success: false, msg: '您没有权限删除文章！' })
    return;
  }

  collect.remove({id: req.query.id});

  article.remove({ _id: req.query.id }).then(() => {
    res.send({ status: 200, success: true, msg: '删除成功！' });
  }).catch(() => {
    res.send({ status: 200, success: false, msg: '删除失败！' });
  })
})
module.exports = router;
